from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from django.db.models import F
from django.http import *
from django.shortcuts import render
from django import forms
from django.utils import timezone


# Create your views here.


class RegisterForm(forms.Form):
    user_name = forms.CharField(label="用户名", max_length=30)
    password1 = forms.CharField(label="密码", max_length=20, widget=forms.PasswordInput)
    password2 = forms.CharField(label="再次输入密码", max_length=20, widget=forms.PasswordInput)
    email = forms.CharField(label="邮箱", max_length=50)


def register_view(request):
    if request.method == 'POST':
        r_form = RegisterForm(request.POST)
        if r_form.is_valid():
            password1 = r_form.cleaned_data['password1']
            password2 = r_form.cleaned_data['password2']
            if password1 != password2:
                result = '两次输入密码不一致'
                return render(request, "user_manage/register.html", locals())
            username = r_form.cleaned_data['user_name']
            email = r_form.cleaned_data['email']
            try:
                user = User.objects.create_user(username=username, password=password1, email=email)
                return HttpResponseRedirect('/user/login')
            except Exception as e:
                result = '用户名或邮箱已被使用'
                return render(request, 'user_manage/register.html', locals())
    else:
        r_form = RegisterForm()
    return render(request, "user_manage/register.html", locals())


class LoginForm(forms.Form):
    username = forms.CharField(label="用户名", max_length=30)
    password = forms.CharField(label="密码", max_length=20, widget=forms.PasswordInput)


def login_view(request):
    if request.method == 'GET':
        l_form = LoginForm()
        return render(request, 'user_manage/login.html', locals())
    elif request.method == 'POST':
        l_form = LoginForm(request.POST)
        if l_form.is_valid():
            username = l_form.cleaned_data['username']
            password = l_form.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if user:
                login(request, user)
                return HttpResponseRedirect('/index')
            else:
                result = '登录失败，您还未注册或账号密码错误'
                return render(request, 'user_manage/login.html', locals())
    else:
        pass
